import { useMemo, useRef } from 'react';

/**
 * 持久化 function 的 Hook
 * @param fn 需要持久化的函数
 * @returns 引用地址永远不会变化的 fn
 */
export function useMemoizedFn(fn) {
  const fnRef = useRef(fn);

  fnRef.current = useMemo(() => fn, [fn]);

  const memoizedFn = useRef();

  if (!memoizedFn.current) {
    memoizedFn.current = function(...args) {
      return fnRef.current.apply(this, args);
    };
  }

  return memoizedFn.current;
}
